package com.jjc.android.fragment

import android.graphics.Color
import android.os.Bundle
import android.view.View
import android.widget.LinearLayout
import android.widget.TextView
import androidx.lifecycle.Observer
import androidx.viewpager2.widget.ViewPager2
import com.jjc.android.Constants
import com.jjc.android.GlobalManager
import com.jjc.android.R
import com.jjc.android.UserManager
import com.jjc.android.activity.HealthRecordsActivity
import com.jjc.android.activity.OperationVideoActivity
import com.jjc.android.adapter.HomeProductAdapter
import com.jjc.android.base.BaseLazyLoadFragment
import com.jjc.android.entity.*
import com.jjc.android.net.SimpleHttpCallback
import com.jjc.android.util.Common
import com.jjc.android.util.Common.formatHtml
import com.jjc.android.util.Common.parseEmpty
import com.jjc.android.util.MultiLanguageUtil
import com.jjc.android.util.dp2px
import com.jjc.android.util.paramEx
import com.jjc.android.view.onClick
import com.lxj.xpopup.util.XPopupUtils
import com.lzy.okgo.OkGo
import com.scwang.smart.refresh.layout.SmartRefreshLayout
import com.zhpan.bannerview.BannerViewPager
import com.zhpan.bannerview.constants.IndicatorGravity
import com.zhpan.bannerview.constants.PageStyle
import com.zhpan.indicator.enums.IndicatorSlideMode
import com.zhpan.indicator.enums.IndicatorStyle
import me.grantland.widget.AutofitTextView
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import kotlin.properties.Delegates

class HomeChildFragment : BaseLazyLoadFragment(),Observer<TestedPersonDto> {

    companion object{
        fun newInstance(primaryClassifyId:String):HomeChildFragment{
            val fragment = HomeChildFragment()
            fragment.arguments = Bundle().apply {
                putString(Constants.BUNDLE_ID,primaryClassifyId)
            }
            fragment.setInflateLazy(true)
            return fragment
        }
    }

    private lateinit var productIntroTxt: TextView
    private lateinit var healthVideoBtn: TextView
    private lateinit var healthDocuBtn: TextView
    private lateinit var productView: BannerViewPager<SecondaryClassifyDto>
    private lateinit var lastRecordLayout: LinearLayout
    private lateinit var lastCheckTimeTxt: TextView
    private lateinit var lastResultTxt: TextView
    private lateinit var lastDateText: AutofitTextView
    private lateinit var lastProductNameText: AutofitTextView
    private lateinit var lastRecordTitle: TextView
    private lateinit var singleLayout:View
    private lateinit var smartRefreshLayout:SmartRefreshLayout
    private lateinit var productBannerAdapter:HomeProductAdapter
    override fun getLayoutId(): Int = R.layout.fragment_home_child
    private var primaryClassifyId:String = ""

    override fun initView(view: View) {
        super.initView(view)
        initViews(view)
        productBannerAdapter = HomeProductAdapter()
        productView.apply {
            registerLifecycleObserver(lifecycle)
            adapter = productBannerAdapter
            setOnPageClickListener({ _: View, position: Int ->

            }, true)
                .setIndicatorStyle(IndicatorStyle.CIRCLE)
                .setIndicatorSlideMode(IndicatorSlideMode.WORM)
                .setIndicatorGravity(IndicatorGravity.CENTER)
                .setIndicatorMargin(0,0,0, 0)
                .setIndicatorHeight(10f.dp2px)
                .setIndicatorSliderWidth(10f.dp2px)
                .setIndicatorSliderColor(Color.parseColor("#4C831CB5"), Color.parseColor("#831CB5"))
                .setScrollDuration(800)
                .setNeedRealPosition(false)
                .registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback(){
                    override fun onPageSelected(position: Int) {
                        productBannerAdapter.onPageSelected(position)
                        currentClassifyDto = productBannerAdapter.getSelected()
                    }
                })
                .setRevealWidth((XPopupUtils.getScreenWidth(requireContext())-256f.dp2px)/2)
                .setPageStyle(PageStyle.MULTI_PAGE_SCALE,0.9f)
                .setAutoPlay(false)
                .create()
        }

        healthDocuBtn.onClick {
            currentClassifyDto?.id?.let {
                HealthRecordsActivity.start(requireContext(),primaryClassifyId,it,(parentFragment as? HomeFragment)?.currentTester?.id)
            }

        }
        healthVideoBtn.onClick {
            currentClassifyDto?.id?.let {
                OperationVideoActivity.start(requireContext(),primaryClassifyId,it)
            }
        }
        smartRefreshLayout.setOnRefreshListener {
            fetchPageInfo()
        }
        showLoadingView(view.findViewById(R.id.childContentLayout))
        currentTester = (parentFragment as? HomeFragment)?.currentTester

    }

    override fun onFragmentResume(firstResume: Boolean) {
        super.onFragmentResume(firstResume)
        fetchPageInfo()
    }

    private var currentTester:TestedPersonDto? by Delegates.observable(null) { _, old, new ->
        if(!ismIsFirstVisible()){
            fetchClassifyDetail()
        }
    }

    private var defaultShowPageClassifyId:String? = null
    fun updateDefaultPage(childClassifyId:String){
        defaultShowPageClassifyId = childClassifyId
        if(ismIsFirstVisible()) return
        updateDefaultPage()
    }

    private var handleDefaultShowPage = false
    private fun updateDefaultPage(){
        if(handleDefaultShowPage||defaultShowPageClassifyId==null) return
        productBannerAdapter.data.let {
            if(!it.isNullOrEmpty()){
                handleDefaultShowPage = true
                it.forEachIndexed { index, secondaryClassifyDto ->
                    val finded = if(defaultShowPageClassifyId.isNullOrEmpty()){
                        "UMA".equals(secondaryClassifyDto.uegppievxbdphngo,true)
                    }else{
                        defaultShowPageClassifyId == secondaryClassifyDto.id
                    }
                    if(finded){
                        productView.currentItem = index
                        return@forEachIndexed
                    }
                }
            }
        }
    }

    override fun onChanged(t: TestedPersonDto?) {
        currentTester = t
    }

    private var currentClassifyDto:SecondaryClassifyDto? by Delegates.observable(null){_,oldValue,newValue->
        if(oldValue?.id == newValue?.id) return@observable
        productIntroTxt.text = newValue?.jsonMember77ewilfzt61i7exb.parseEmpty(getString(R.string.no_temp_txt))
        fetchClassifyDetail()
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onMessageEvent(event: HealthRecordChangeEvent){
        fetchClassifyDetail()
    }

    override fun isHaveEventBus(): Boolean {
        return true
    }

    private fun fetchClassifyDetail(){
        val tester = currentTester?:return
        val classify = currentClassifyDto?:return
        OkGo.post<LzyResponse<HealthRecordDto>>(Constants.getLatelyHealthRecordDetails)
            .paramEx(mutableMapOf(
                "tuoTuToken" to UserManager.userInfo().tuoTuToken,
                "tuoTuUserId" to UserManager.userId(),
                "detectionUserId" to tester.id,
                "minorTermId" to classify.id
            ))
            .tag(this)
            .execute(object : SimpleHttpCallback<LzyResponse<HealthRecordDto>>(false){
                override fun onCallSuccess(response: LzyResponse<HealthRecordDto>) {
                    if(response.data!=null){
                        val report = response.data
                        lastRecordTitle.visibility = View.VISIBLE
                        lastRecordLayout.visibility = View.VISIBLE
                        lastProductNameText.text = report.minorTermName.parseEmpty()
                        lastDateText.text = report.collectDate
                        lastResultTxt.text = report.primaryResDisplay.parseEmpty("暂无")
                        lastCheckTimeTxt.text = String.format("%s: %s",getString(R.string.last_dete_time_txt),report.nextCollectDate.parseEmpty())
                    }else{
                        lastRecordTitle.visibility = View.GONE
                        lastRecordLayout.visibility = View.GONE
                    }
                }

                override fun onCallError(error: String?) {
                    super.onCallError(error)
                    lastRecordTitle.visibility = View.GONE
                    lastRecordLayout.visibility = View.GONE
                }
            })
    }

    override fun fetchPageInfo() {
        OkGo.post<LzyResponse<PageInfo<SecondaryClassifyDto>>>(Constants.getFormList)
            .paramEx(mutableMapOf(
                "page" to 1,
                "pagesize" to 100,
                "needpage" to "1",
                "formheaduuid" to "0f078bd3ef0946548f6e18b1f245f8c3",
                "isasc" to true,
                "sortid" to "wfwx0dlcvkpojft1",
                "filters" to listOf<KeyValuePair>(
                    KeyValuePair("jysnwnlyigidwpaf",primaryClassifyId),
                    KeyValuePair("zxrqekxhvs1pdyik", MultiLanguageUtil.getInstance().getValue("1a36aa83-fec3-40c6-82e7-f5256dd23ca0","439d966f-54f5-42f0-94ad-f4df2801701a")),
                    KeyValuePair("gwkora0c5jwdubgf","9c6bbabb-d61b-43e8-936f-6d8330b76b85")
                )
            ),true)
            .tag(this)
            .execute(object : SimpleHttpCallback<LzyResponse<PageInfo<SecondaryClassifyDto>>>(false){
                override fun onCallSuccess(response: LzyResponse<PageInfo<SecondaryClassifyDto>>) {
                    if(!response.data?.data.isNullOrEmpty()){
                        hideLoadingView()
                        if(response.data?.data?.size==1){
                            productView.visibility = View.GONE
                            singleLayout.visibility = View.VISIBLE
                            currentClassifyDto = response.data.data[0]
                            singleLayout.apply {
                                findViewById<TextView>(R.id.productNameTxt).text =
                                    currentClassifyDto?.ribhfqebw2sqjovu
                                findViewById<TextView>(R.id.prductSubTxt).text = currentClassifyDto?.uegppievxbdphngo
                                findViewById<View>(R.id.tagImage).visibility = View.VISIBLE
                            }
                        }else{
                            var findIndex = 0
                            if(currentClassifyDto!=null){
                                response.data.data.forEachIndexed{ index, secondaryClassifyDto ->
                                    if(currentClassifyDto?.id == secondaryClassifyDto.id){
                                        findIndex = index
                                        return@forEachIndexed
                                    }
                                }
                            }
                            currentClassifyDto = response.data.data[findIndex]
                            productView.refreshData(response.data.data,findIndex)

                            productView.visibility = View.VISIBLE
                            singleLayout.visibility = View.GONE

                            updateDefaultPage()
                        }

                    }else{
                        currentClassifyDto = null
                        showEmptyView(getString(R.string.no_cate_txt))
                    }
                    smartRefreshLayout.finishRefresh()
                }

                override fun onCallError(error: String?) {
                    super.onCallError(error)
                    showErrorView(error)
                    smartRefreshLayout.finishRefresh()
                }
            })
    }

    override fun setupArguments(args: Bundle?) {
        primaryClassifyId = args?.getString(Constants.BUNDLE_ID)?:""
    }

    private fun initViews(view: View) {
        singleLayout = view.findViewById(R.id.singleLayout)
        productView = view.findViewById(R.id.productView)
        healthDocuBtn = view.findViewById(R.id.healthDocuBtn)
        healthVideoBtn = view.findViewById(R.id.healthVideoBtn)
        productIntroTxt = view.findViewById(R.id.productIntroTxt)
        lastRecordTitle = view.findViewById(R.id.lastRecordTitle)
        lastProductNameText = view.findViewById(R.id.lastProductNameText)
        lastDateText = view.findViewById(R.id.lastDateText)
        lastResultTxt = view.findViewById(R.id.lastResultTxt)
        lastCheckTimeTxt = view.findViewById(R.id.lastCheckTimeTxt)
        lastRecordLayout = view.findViewById(R.id.lastRecordLayout)
        smartRefreshLayout = view.findViewById(R.id.smartRefreshLayout)
    }
}